package com.hcinfos.gsoo.ui;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.baidu.location.LocationClient;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.CityAdapter;
import com.hcinfos.gsoo.adapter.CityExpandableAdapter;
import com.hcinfos.gsoo.adapter.SearchCityAdapter;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.db.DBUtil;
import com.hcinfos.gsoo.enity.Area;
import com.hcinfos.gsoo.enity.City;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.json.CityJson;
import com.hcinfos.gsoo.service.LocationService;
import com.hcinfos.gsoo.util.CommonUtil;
import com.hcinfos.gsoo.util.DateUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.view.MyLetterView;
import com.hcinfos.gsoo.view.MyLetterView.OnTouchingLetterChangedListener;

public class CityListActivity extends Activity implements
		OnTouchingLetterChangedListener, OnClickListener {

	private TextView location_tv;
	private TextView center_tv;
	private ExpandableListView cityListView;

	private DBUtil dbUtil;
	private Editor editor;
	private CityExpandableAdapter cityAdapter;
	private List<String> aphaList;
	private List<List<City>> cityList;
	public Context context;
	private MyLetterView myView;
	private TextView tvLetter;

	private RelativeLayout left_rl;
	private RelativeLayout right_rl;
	private TextView position_tv;
	private ImageButton backIB;

	private boolean mIsStart = false;

	private final int GET_CITY_SUCCESS = 0x1120;
	private final int GONE_LETTERVIEW = GET_CITY_SUCCESS + 1;
	private final int CHECK_ISSEARCH = GET_CITY_SUCCESS + 2;
	private final int GET_CITY_EMPTY = GET_CITY_SUCCESS + 3;
	private final int GET_CITY_ERROR = GET_CITY_SUCCESS + 4;
	private final int GET_CITY_SERVER_SUCCESS = GET_CITY_SUCCESS + 5;
	private final int CHANGE_CITY_ERROR = GET_CITY_SUCCESS + 6;// 城市切换失败
	private final int CHANGE_CITY_SUCCESS = GET_CITY_SUCCESS + 7;
	private final int ENTER_HOME = GET_CITY_SUCCESS + 8;

	private TextView city_tv;
	private AutoCompleteTextView auto_tv;
	private SearchCityAdapter searchCityAdapter;
	private int type = -1;// -1 定位 1 搜索
	private RelativeLayout list_rl, search_rl;
	private ListView search_listView;
	private CityAdapter resultAdapter;
	private PopupWindow resultWindow;
	private List<Area> result_citys;
	private SharePreferenceUtil util;
	private List<City> resultList;
	private LayoutInflater lif;
	private RelativeLayout progress_layout;
	private LinearLayout loading_dialog_content_layout;
	private RelativeLayout loading_staus_rl;
	private City changeCity;
	private InputMethodManager imm;
	private Dialog waitDialog;

	private boolean isSameCity = true;
	
	private LocationClient locationClient;


	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		locationClient = ((GsooApplication)getApplication()).mLocationClient;
		IntentFilter filter = new IntentFilter(LocationService.LOCATION_ACTION);
		registerReceiver(receiver, filter);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		setContentView(R.layout.activity_city);
		waitDialog = DialogUtil.createWaitDialog(this, "城市切换中...");
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		this.context = this;
		util = new SharePreferenceUtil(this, "setting");
		dbUtil = DBUtil.newInstance(this);
		result_citys = new ArrayList<Area>();
		initRes();
		if (GsooApplication.cityName == null) {
			city_tv.setText("正在定位中...");
		}
		//
		locationClient.start();
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			city_tv.setText(GsooApplication.cityName);
		}
	};

	private void initRes() {

		backIB = (ImageButton) findViewById(R.id.left_ib);
		backIB.setOnClickListener(this);
		backIB.setBackgroundResource(R.drawable.wb_btn_off);

		position_tv = (TextView) findViewById(R.id.reg_tv);
		position_tv.setOnClickListener(this);
		left_rl = (RelativeLayout) findViewById(R.id.left);
		// left_rl.setOnClickListener(this);
		location_tv = (TextView) findViewById(R.id.reg_tv);
		location_tv.setText("定位");
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("城市列表");

		lif = LayoutInflater.from(this);
		View headView = lif.inflate(R.layout.city_headview, null);
		auto_tv = (AutoCompleteTextView) headView.findViewById(R.id.auto_tv);
		city_tv = (TextView) headView.findViewById(R.id.city_tv);
		city_tv.setText("正在定位中..");
		city_tv.setOnClickListener(this);
		auto_tv.addTextChangedListener(autoListener);
		// auto_tv.setThreshold(1);
		// headView.setOnClickListener(this);

		aphaList = new ArrayList<String>();
		cityList = new ArrayList<List<City>>();
		cityListView = (ExpandableListView) findViewById(R.id.cityListView);
		cityListView.addHeaderView(headView);
		cityListView.setTextFilterEnabled(true);
		cityAdapter = new CityExpandableAdapter(cityList, aphaList, context);
		cityListView.setAdapter(cityAdapter);
		cityListView.setOnGroupClickListener(new OnGroupClickListener() {
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				return true;
			}
		});
		cityListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				tvLetter.setVisibility(View.GONE);
				if (locationCityName != null
						&& locationCityName.equals(changeCity.getName())) {
					isSameCity = true;
				} else {
					isSameCity = false;
				}

				GsooApplication.currentCity = cityList.get(groupPosition).get(
						childPosition);
				changeCity = cityList.get(groupPosition).get(childPosition);
				handler.sendEmptyMessage(ENTER_HOME);
				return false;
			}
		});

		myView = (MyLetterView) findViewById(R.id.myView);
		myView.setOnTouchingLetterChangedListener(this);

		tvLetter = (TextView) findViewById(R.id.tvLetter);
		tvLetter.setVisibility(View.GONE);

		list_rl = (RelativeLayout) findViewById(R.id.list_rl);
		list_rl.setVisibility(View.GONE);
		initSearch();
		progress_layout = (RelativeLayout) findViewById(R.id.progress_layout);
		progress_layout.setOnClickListener(this);
		loading_dialog_content_layout = (LinearLayout) findViewById(R.id.loading_dialog_content_layout);
		loading_staus_rl = (RelativeLayout) findViewById(R.id.loading_staus_rl);
		loading_staus_rl.setVisibility(View.GONE);// 内容提示
		loading_dialog_content_layout.setVisibility(View.VISIBLE);// 加载条
	}

	private void changeCity(final String cityId) {
		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							context, Urls.CHANGE_CITY + "cityId=" + cityId);
					LogUtil.d("wxf", "change_city:" + result);
					if (result == null) {
						Message msg = handler.obtainMessage();
						msg.what = CHANGE_CITY_ERROR;
						handler.sendMessage(msg);
					} else {
						if (result.replaceAll("\\s*|\t|\r|\n", "").equals(
								"success")) {
							Message msg = handler.obtainMessage();
							msg.what = CHANGE_CITY_SUCCESS;
							handler.sendMessage(msg);
						} else {
							Message msg = handler.obtainMessage();
							msg.what = CHANGE_CITY_ERROR;
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					LogUtil.d("wxf", "e:" + e.toString());
					Message msg = handler.obtainMessage();
					msg.what = CHANGE_CITY_ERROR;
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	// 搜索
	private void initSearch() {
		resultList = new ArrayList<City>();
		resultAdapter = new CityAdapter(context, resultList);
		resultView = lif.inflate(R.layout.result_city, null);
		listView = (ListView) resultView.findViewById(R.id.listView);
		listView.setAdapter(resultAdapter);
		listView.setOnItemClickListener(resultItemClickListener);
	}

	/**
	 * obtain data from server
	 */
	private int page = 1;
	private int rows = 2000;

	private void obtainCityList() {

		new Thread(new Runnable() {

			@Override
			public void run() {

				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							context, Urls.CITY_LIST + "page=" + page + "&rows="
									+ rows);
					if (result == null) {
						Message msg = handler.obtainMessage();
						msg.what = GET_CITY_ERROR;
						handler.sendMessage(msg);
					} else {
						result_citys = CityJson.getCityListByJson(result);
						if (result_citys.size() > 0) {
							Message msg = handler.obtainMessage();
							msg.what = GET_CITY_SERVER_SUCCESS;
							handler.sendMessage(msg);
						}
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = GET_CITY_ERROR;
					handler.sendMessage(msg);
					LogUtil.d("wxf", "e:" + e.toString());
				}
			}
		}).start();
	}

	private Intent intent;
	OnItemClickListener resultItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			City city = resultList.get(position);
			if (resultWindow != null)
				resultWindow.dismiss();
			if (waitDialog != null)
				waitDialog.show();

			GsooApplication.cityCode = city.getCityId();
			if (locationCityName != null
					&& locationCityName.equals(city.getName())) {
				GsooApplication.isSameCity = true;
				isSameCity = true;
			} else {
				GsooApplication.isSameCity = false;
				isSameCity = false;
			}
			changeCity(city.getCityId());
			GsooApplication.currentCity = city;
			changeCity = city;

		}
	};

	private TextWatcher autoListener = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			String name = s.toString();
			Cursor cursor = dbUtil.selectNameByKeyWord(name);
			LogUtil.d("wxf", "cursor:" + cursor.getColumnCount());
			searchCityAdapter = new SearchCityAdapter(CityListActivity.this,
					cursor, true);
			auto_tv.setAdapter(searchCityAdapter);
			searchCityAdapter.notifyDataSetChanged();
			if (s.length() > 0) {
				Message msg = handler.obtainMessage();
				msg.what = CHECK_ISSEARCH;
				msg.obj = 1;
				handler.sendMessage(msg);
			} else {
				Message msg = handler.obtainMessage();
				msg.what = CHECK_ISSEARCH;
				msg.obj = -1;
				handler.sendMessage(msg);
			}

		}
	};

	@Override
	protected void onResume() {
		result_citys.clear();
		mIsStart = true;
		boolean isUpdate = util.loadBooleanSharedPreference("isUpdateCity",
				false);
		String currentTime = DateUtil.getCurrentTime();
		String lastUpdateTime = util
				.loadStringSharedPreference("isLastUpdateCityTime");
		int days = 0;
		if (lastUpdateTime == null) {
			isUpdate = false;
		} else {
			try {
				days = Math.abs(DateUtil.daysBetween(currentTime,
						lastUpdateTime));
				LogUtil.d("wxf", "days:" + days);
				if (days >= 1) {
					isUpdate = false;
				}
			} catch (ParseException e) {
				LogUtil.d("wxf", "e:" + e.toString());
				isUpdate = false;
			}
		}

		if (!isUpdate) {
			// request
			obtainCityList();
		} else {
			// query from db
			queryCityFromDb();
		}
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	}

	/**
	 * 从数据库里面查询城市数据
	 */
	public void queryCityFromDb() {
		aphaList.clear();
		cityList.clear();
		List<String> list = dbUtil.queryCityIndex();
		for (int i = 0; i < list.size(); i++) {
			aphaList.add(list.get(i));
			List<City> cList = dbUtil.queryCityListByIndex(list.get(i));
			cityList.add(cList);
		}
		cityAdapter.setDataChange(cityList, aphaList);
		int count = cityAdapter.getGroupCount();
		for (int i = 0; i < count; i++) {
			cityListView.expandGroup(i);
		}
		progress_layout.setVisibility(View.GONE);// 加载的隐藏
		list_rl.setVisibility(View.VISIBLE);
	}

	@Override
	public void onTouchingLetterChanged(String s) {
		if (s.equals("#")) {
			tvLetter.setText("搜索");
			cityListView.setSelectedGroup(-1);
		}
		if (alphaIndexer(s) > -1) {
			int position = alphaIndexer(s);
			cityListView.setSelectedGroup(position);
			tvLetter.setText(s);
			tvLetter.setVisibility(View.VISIBLE);
		}
	}

	public int alphaIndexer(String s) {
		for (int i = 0; i < aphaList.size(); i++) {
			if (aphaList.get(i).equals(s)) {
				return i;
			}
		}
		return -1;
	}

	private String locationCityName = null;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case GONE_LETTERVIEW:
				tvLetter.setVisibility(View.GONE);
				break;
			case GET_CITY_SUCCESS:
				locationCityName = (String) msg.obj;
				if (locationCityName == null) {
					city_tv.setText("定位失败");
				} else {
					city_tv.setText(locationCityName);
				}
				break;
			case CHECK_ISSEARCH:
				type = (Integer) msg.obj;
				if (type > 0) {
					location_tv.setText("搜索");
				} else {
					location_tv.setText("定位");
				}
				break;
			case GET_CITY_SERVER_SUCCESS:
				updateData();
				break;
			case GET_CITY_ERROR:
				loading_staus_rl.setVisibility(View.VISIBLE);
				loading_dialog_content_layout.setVisibility(View.GONE);
				break;
			case CHANGE_CITY_SUCCESS:
				if (changeCity == null)
					return;

				obtainType();
				break;
			case CHANGE_CITY_ERROR:
				if (waitDialog != null)
					waitDialog.dismiss();
				Toast.makeText(context, "切换失败,请重新再试!", 500).show();
				break;
			case ENTER_HOME:
				GsooApplication.isShowTipChangeCity = false;
				util.saveSharedPreferences("cityName", changeCity.getName());
				util.saveSharedPreferences("cityId", changeCity.getCityId());
				if (waitDialog != null)
					waitDialog.dismiss();
				intent = new Intent(CityListActivity.this,
						MainTabActivity.class);
				if (isSameCity) {
					GsooApplication.cityName = changeCity.getName();
				}
				GsooApplication.isSameCity = isSameCity;
				GsooApplication.cacheGroupList = null;
				GsooApplication.cacheSupExtList = null;
				GsooApplication.currentCity = changeCity;
				util.saveObject(changeCity, "city");
				HomeActivity.isChangeData = true;
				startActivity(intent);
				finish();
				break;
			}
		};
	};

	private void obtainType() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String result = HttpClientUtil.getFromWebByHttpClient(
							context, Urls.GET_ALL_TYPE);
					LogUtil.d("wxf", "result:" + result);
					GsooApplication.cacaheMap.remove(Urls.GET_ALL_TYPE);
					GsooApplication.cacaheMap.put(Urls.GET_ALL_TYPE, result);
					Message msg = handler.obtainMessage();
					msg.what = ENTER_HOME;
					handler.sendMessage(msg);
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = ENTER_HOME;
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	@Override
	public void onTouchUp() {

		handler.sendEmptyMessageDelayed(GONE_LETTERVIEW, 500);
	}

	/**
	 * 更新数据
	 */
	private void updateData() {
		List<City> tempCitys = new ArrayList<City>();
		for (Area area : result_citys) {
			City city = new City();
			city.setCityId(area.getId());
			city.setName(area.getAreaName());
			String pingying = area.getPinyin();
			if (area.getAreaName().equals("长沙市")) {
				Log.d("wxf", "pinyin=" + area.getPinyin());
			}
			if (pingying == null || pingying.length() == 0) {
				city.setIndex(CommonUtil.getPinYinHeadChar(area.getAreaName()));
			} else {
				city.setIndex((String.valueOf(pingying.charAt(0)))
						.toUpperCase());
			}
			tempCitys.add(city);
		}
		dbUtil.insertCityList(tempCitys);
		util.saveSharedPreferences("isLastUpdateCityTime",
				DateUtil.getCurrentTime());
		util.saveSharedPreferences("isUpdateCity", true);
		queryCityFromDb();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_ib:
			Intent intent = new Intent(CityListActivity.this,
					MainTabActivity.class);
			startActivity(intent);
			finish();
			break;
		case R.id.reg_tv:
			cityListView.setSelectedGroup(-1);
			imm.hideSoftInputFromWindow(auto_tv.getWindowToken(), 0);
			if (type > 0) {
				resultList = dbUtil.queryCityByKeyWord(auto_tv.getText()
						.toString());
				if (resultWindow == null) {
					resultWindow = getResultWindow();
				}
				resultWindow.showAtLocation(
						CityListActivity.this.findViewById(R.id.main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
				resultAdapter.setDataChange(resultList);

			} else {
				city_tv.setText("重新定位中...");
			}
			break;
		case R.id.city_tv:
			if (waitDialog != null)
				waitDialog.show();
			String name = city_tv.getText().toString();
			if (name == null || name.length() == 0)
				return;
			City city = dbUtil.queryCityByCityName(name);
			if (city == null) {
				waitDialog.dismiss();
				Toast.makeText(context, "该城市未开通", 500).show();
				return;
			} else {
				GsooApplication.currentCity = city;
				GsooApplication.isSameCity = true;
				changeCity = city;
				changeCity(city.getCityId());
			}
			break;
		case R.id.progress_layout:
			loading_staus_rl.setVisibility(View.GONE);// 内容提示
			loading_dialog_content_layout.setVisibility(View.VISIBLE);// 加载条
			obtainCityList();
			break;
		}
	}

	/**
	 * search popwindow
	 * 
	 */

	private ListView listView;
	private View resultView;;

	public PopupWindow getResultWindow() {
		final PopupWindow resultWindow = new PopupWindow();
		// 设置按钮监听
		// 设置SelectPicPopupWindow的View
		resultWindow.setContentView(resultView);
		// 设置SelectPicPopupWindow弹出窗体的宽
		resultWindow.setWidth(LayoutParams.FILL_PARENT);
		// 设置SelectPicPopupWindow弹出窗体的高
		resultWindow.setHeight(LayoutParams.WRAP_CONTENT);
		// 设置SelectPicPopupWindow弹出窗体可点击
		resultWindow.setFocusable(true);
		// 设置SelectPicPopupWindow弹出窗体动画效果
		resultWindow.setAnimationStyle(R.style.AnimBottom);
		// 实例化一个ColorDrawable颜色为半透明
		ColorDrawable dw = new ColorDrawable(Color.argb(125, 0, 0, 0));
		// 设置SelectPicPopupWindow弹出窗体的背景
		resultWindow.setBackgroundDrawable(dw);
		// mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
		resultView.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				int height = resultView.findViewById(R.id.pop_rl).getTop();
				int y = (int) event.getY();
				if (event.getAction() == MotionEvent.ACTION_UP) {
					if (y < height) {
						resultWindow.dismiss();
					}
				}
				return true;
			}
		});
		return resultWindow;
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent(CityListActivity.this,
					MainTabActivity.class);
			startActivity(intent);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
}
